const cheerio = require('cheerio');
const url = require("url");
var vm = require('vm');
const { loadContent } = require('../request');

function homepage(content) {
    const $ = cheerio.load(content);
    // 目录
    const aEles = $('ul.type-slide').find('a')
    const menu = [];
    for (let index = 0; index < aEles.length; index++) {
        const aEle = aEles[index];
        var href = aEle.attribs['href'];
        const title = aEle.children[0].data;
        if (title == '理论片') {
            href = '/tag/3-----------.html';
        }
        menu.push({ title, href, hrefType: "videoList" });
    }
    /* const aEles1 = $('ul.tag-btn').find('a');
    for (let index = 0; index < aEles1.length; index++) {
        const aEle = aEles1[index];
        const href = aEle.attribs['href'];
        const find = menu.find((value) => value.href == href)
        if (!find) {
            const title = aEle.children[0].data;
            menu.push({ title, href });
        }
    } */
    // 首页推荐 分类
    const types = [];
    const childAll = $('.stui-pannel');
    for (let index = 0; index < childAll.length - 1; index++) {
        const element = $(childAll[index]);
        var result = element.find('h3.title')
        if (result.length > 0) {
            const h3Ele = $(result[0]);
            var title = h3Ele.text().trim();
            var imagePath = h3Ele.find('img').attr('src');
            var href = h3Ele.find('a').attr('href');
            const aEle = element.find('a.more')[0];
            const findMenu = menu.find(value => value.title == title);
            if (findMenu) {
                findMenu.href = aEle.attribs['href'];
            }
            // console.log(title)
            const itemEles = element.find('div.stui-vodlist__box');
            const items = []
            for (let index1 = 0; index1 < itemEles.length; index1++) {
                const element = $(itemEles[index1]);
                const itemAEle = element.find('a.stui-vodlist__thumb')[0];
                const itemHref = decodeURI(itemAEle.attribs['href']);
                const hint = $(itemAEle).find('span.pic-text').text().trim();
                items.push({
                    title: itemAEle.attribs['title'],
                    hint,
                    href: itemHref,
                    hrefType: "videoInfo",
                    playHref: loadPlayHref(itemHref),
                    imagePath: itemAEle.attribs['data-original'],
                });
            }
            const bean = { title, imagePath, href, hrefType: 'videoList', children: items };
            types.push(bean);
        }
    }
    // console.log(JSON.stringify({ menu, types }, null, 4));
    return { menu, children: types };
}

function videoList(content) {
    const $ = cheerio.load(content);
    var ulEles = $('ul.stui-screen__list')
    const menu = [];
    for (let index = 0; index < ulEles.length; index++) {
        const ulEle = $(ulEles[index]);
        const title = ulEle.find('span').text();
        // console.log(title);
        const aEles = ulEle.find('a')
        var children = [];
        for (let index = 0; index < aEles.length; index++) {
            const a = aEles[index];
            var active = $(a.parent).hasClass('active');
            if (a.children.length > 0) {
                children.push({
                    href: decodeURI(a.attribs['href']),
                    hrefType: "videoList",
                    title: a.children[0].data,
                    active,
                });
            }
        }
        if (children.length > 1) {
            menu.push({ title, children });
        }
    }
    var aEles = $('div.stui-pannel__head ul a');
    var children = [];
    for (let index = 0; index < aEles.length; index++) {
        const a = aEles[index];
        if (a.children.length > 0) {
            children.push({
                href: decodeURI(a.attribs['href']),
                hrefType: "videoList",
                title: a.children[0].data,
                active: $(a.parent).hasClass('active'),
            });
        }
    }
    menu.push({ title: '其他', children });
    const divEles = $('div.stui-vodlist__box');
    const list = [];
    for (let index = 0; index < divEles.length; index++) {
        const divEle = $(divEles[index]);
        const a = divEle.find('a')[0];
        const p = $(divEle.find('p.text')[0]);
        list.push({
            title: a.attribs['title'],
            href: a.attribs['href'],
            playHref: loadPlayHref(a.attribs['href']),
            hrefType: "videoInfo",
            imagePath: a.attribs['data-original'],
            hint: $(a).text().trim(),
            synopsis: p.text().trim(),
        });
    }
    return { menu, children: list, page: parsePage($) };
}

function loadPlayHref(href) {
    return href.replace('.html', '').replace('/py-', '/mov-') + '-1-1.html';
}

function videoInfo(content) {
    const $ = cheerio.load(content);
    const title = $('div.stui-content__thumb a').attr('title');
    const imagePath = $('div.stui-content__thumb a img').attr('data-original');
    const hint = $('div.stui-content__thumb a span.pic-text').text().trim();
    const pEles = $('p.data');
    const score = $(pEles[0]).text().trim().replace(/\s+/g, '；');
    const actor = $(pEles[1]).text().trim() + ' ' + $(pEles[2]).text().trim() + ' ';
    const synopsis = $('span.detail-content').text().trim();
    const href = $('a.btn.btn-primary').attr('href');
    return { title, imagePath, hint, href, hrefType: "videoPlayPath", score, actor: actor.replace(/\s+/g, '；') + $(pEles[3]).text().trim(), synopsis }
}

async function videoPlayPath(content, tag) {
    var infoList = loadPreVideoPath(content, tag);
    const preVideoPath = infoList.url;
    if (preVideoPath.endsWith('.m3u8')) {
        return { list: infoList.list, videoPath: { url: preVideoPath }, synopsis: infoList.synopsis, title: infoList.vod_name, nowPart: infoList.vod_part };
    }
    var q = url.parse(preVideoPath, true);
    var newHost = q.protocol + "//" + q.host + "";
    try {
        const newContent = await loadContent(preVideoPath, tag, 'videoPlayPath');
        var videoPath = newHost + loadVideoPath(newContent);
        return { list: infoList.list, videoPath: { url: videoPath }, synopsis: infoList.synopsis, title: infoList.vod_name, nowPart: infoList.vod_part };
    } catch (error) {
        // console.log(error);
        return { list: infoList.list, videoPath: { error: `${error}` }, synopsis: infoList.synopsis, title: infoList.vod_name, nowPart: infoList.vod_part };
    }
}

function loadPreVideoPath(content, tag) {
    // https://vod6.bdzybf7.com/share/rUHnOrhJWyzCxfD1
    const $ = cheerio.load(content);
    const synopsis = $('span.detail-content').text().trim();
    const ulEles = $('ul.stui-content__playlist');
    const list = [];
    const titleEles = $('div.stui-pannel-box.b h3.title');
    for (let index = 0; index < ulEles.length; index++) {
        const liEles = $(ulEles[index]).find('li');
        const title = titleEles[index].children[0].data;
        const items = []
        for (let index = 0; index < liEles.length; index++) {
            const liEle = liEles[index];
            const className = liEle.attribs['class'];
            const aEle = $(liEle).find('a')[0];
            const href = aEle.attribs['href'];
            items.push({ active: className ? true : false, href, hrefType: 'videoPlayPath', title: aEle.children[0].data });
        }
        var bean = {};
        bean[title] = items;
        list.push(bean);
    }
    const infoScript = $('script').filter((_, value) => $(value).text().indexOf('vod_name') > -1);
    var script = $('script').filter((_, value) => $(value).text().indexOf('player_aaaa') > -1);
    var player_data_tag = false;
    if (!script || script.length == 0) {
        script = $('script').filter((_, value) => $(value).text().indexOf('player_data') > -1);
        player_data_tag = true;
    }
    // 
    // var player_aaaa = { "flag": "play", "enc....
    const item = script.text().trim() + ';\n' + infoScript.text().trim().replace('vod_url = window.location.href,', '');
    var fun = new vm.Script(item);
    fun.runInThisContext();
    var aaaa;
    if(player_data_tag){
        aaaa = player_data;
        aaaa.vod_name = $('div.play_vlist_text.vnow div p')[0].children[0].data;
        aaaa.vod_part = $('div.play_vlist_text.vnow p.play_vlist_now').text();
    }else{
        aaaa = player_aaaa;
        aaaa.vod_name = vod_name;
        aaaa.vod_part = vod_part;
    }
    aaaa.list = list;
    aaaa.synopsis = synopsis;
    return aaaa;
}

function loadVideoPath(content) {
    const $ = cheerio.load(content);
    const script = $('script').filter((_, value) => $(value).text().indexOf('main') > -1);
    var item = script.text().trim();
    var index = item.indexOf('$');
    if (index > -1) {
        item = item.substring(0, index);
    }
    // console.log(item);
    eval(item);
    return main;
}


function searchVideo(content) {
    const $ = cheerio.load(content);
    const searchTxt = $($('div.col-lg-wide-75 div.stui-pannel__head h3.title')[0]).text().trim();
    const liEles = $('div.col-lg-wide-75 ul.stui-vodlist__media li');
    const children = [];
    for (let index = 0; index < liEles.length; index++) {
        const liEle = $(liEles[index]);
        const hint = liEle.find('span.pic-text').text().trim();
        const title = liEle.find('div.detail h3.title a').text().trim();
        const pEles = liEle.find('div.detail p');
        const actor = $(pEles[0]).text().trim() + '；' + $(pEles[1]).text().trim();
        const score = $(pEles[2]).text().trim();
        const aEles = $(pEles[3]).find('a');
        const href = aEles[0].attribs['href'];
        const imagePath = liEle.find('div.thumb a')[0].attribs['data-original'];
        const infoHref = aEles[1].attribs['href'];
        children.push({ title, hint, score: formSpace(score), actor: formSpace(actor), href, hrefType: 'videoPlayPath', infoHref, imagePath });
    }
    return { title: searchTxt, children, page: parsePage($) };
}

function formSpace(content) {
    return content.replace(/\n/g, ' ').replace(/\s+/g, '；').replace(/：；/g, '：');
}

function parsePage($) {
    var spanEle = $('ul.stui-page li.visible-xs span');
    if (spanEle.length < 1) {
        return undefined;
    }
    const numTxt = spanEle.text().trim();
    if (numTxt) {
        var array = numTxt.split('/');
        const page = parseInt(array[0]);
        const pageSize = parseInt(array[1]);
        const hrefAEles = $('ul.stui-page li a').filter((_, value) => {
            return value.attribs['rel'];
        });
        const lastHref = decodeURI(hrefAEles[0].attribs['href']);
        const nextHref = decodeURI(hrefAEles[1].attribs['href']);
        const endHref = decodeURI(hrefAEles[2].attribs['href']);
        return { page, pageSize, lastHref, nextHref, endHref };
    }
    return undefined;
}

module.exports = { homepage, videoList, videoInfo, videoPlayPath, searchVideo }